<template>
  <a-modal :open="open" width="900px" centered :footer="null" @cancel="onCancel">
    <template #title>
      <div class="flex items-start pr-20">
        <span class="w-[130px]"> {{ patientInfo?.isNmiYbdj ? '撤销医保登记' : '医保登记' }} </span>
        <a-radio-group v-model:value="tabActiveKey" button-style="solid" size="large" class="flex-1 -mt-2 flex justify-center" @change="onTabRadioChange">
          <a-radio-button v-for="(item, index) in filterType()" :key="index" :value="item.name">{{ item.name }}</a-radio-button>
        </a-radio-group>
      </div>
    </template>
    <div class="bg-secondary w-full p-4 rounded-md border border-solid border-primary">
      <div class="flex items-end">
        <div class="flex items-end w-[240px]">
          <div class="text-lg font-semibold text-primary">{{ formState?.brName }}</div>
          <div class="mx-3">{{ formState?.brXb }}</div>
          <div>{{ formState?.brAge || '-' }}</div>
        </div>
        <LabelValue label="入院时间" :width="240" :value="formState?.admissionTime" />
      </div>
      <div class="flex items-center mt-2">
        <LabelValue label="待入病区" :width="240" :value="formState?.wardName" />
        <LabelValue label="目标床位" :width="240" :value="formState?.bedCode" />
        <LabelValue label="入院途径" :width="240" :value="formState?.dictItemName" />
      </div>
      <div class="flex items-center mt-2">
        <LabelValue label="入院诊断" :width="480" tooltip :value="formState?.ryzd" />
        <LabelValue label="出院诊断" :width="240" tooltip :value="formState?.cyzd" />
      </div>
    </div>
    <div class="flex justify-between p-2 w-full overflow-hidden">
      <div class="flex-1">
        <div class="flex justify-end items-center mb-3">
          <a-input
            v-if="tabActiveKey === '电子凭证'"
            v-model:value="formState.ck"
            placeholder="请扫描电子凭证"
            class="w-[360px]"
            @keyup.enter="readYbSrzCard(false)"
          />
          <div class="flex flex-1 justify-end">
            <a-button class="" type="primary" @click="readYbSrzCard(false)">读卡</a-button>
            <a-input v-if="inAreaCode === '02' && tabActiveKey === '身份证'" v-model:value="idNumber" class="w-[200px] ml-2" placeholder="请输入身份证号" />
            <a-button v-if="inAreaCode === '02' && tabActiveKey === '身份证'" type="primary" class="ml-2" @click="readYbSrzCard(true)">无卡识别</a-button>
          </div>
        </div>
        <div class="flex">
          <div class="w-1/2">
            <LabelValue label="社保卡号" class="mb-2 font-bold" tooltip :width="260" :value="readFormState?.kh" />
            <LabelValue label="身份证号" class="mb-2" tooltip :width="240" :value="readFormState?.brSfz" />
            <LabelValue label="就诊凭证编号" class="mb-2" tooltip :width="300" :value="readFormState?.mdtrtCertNo" />
            <div class="flex items-center mb-2">
              <div class="w-[80px]">险种类别：</div>
              <a-input v-model:value="checkInsutypeName.insutypeName" class="w-[230px]" placeholder="险种类别" allow-clear @click="onClickInsutypeName(true)" />
            </div>
            <div class="flex items-center">
              <div class="w-[82px] relative"><span class="text-red-500 absolute top-0 -left-2">*</span> 医疗类别：</div>
              <!-- <SelectSection v-model:value="formState.inpTypeCode" class="w-[230px]" :search-params="{ yxzt: '0' }" /> -->
              <SelectItem
                v-model:value="formState.med_type"
                class="!w-[230px]"
                type="med_type"
                :params="{ type: '住院' }"
                trigger="init"
                placeholder="请选择"
              />
            </div>
          </div>
          <div class="w-1/2">
            <LabelValue label="卡识别码" class="mb-2" tooltip :width="340" :value="readFormState?.ksbm_new" />
            <LabelValue label="病历卡号" class="mb-2" tooltip :width="240" :value="readFormState?.brBlkh" />
            <LabelValue label="所属统筹区" class="mb-2" tooltip :width="260" :value="checkInsutypeName?.insuplc_admdvs" />
            <div class="flex items-center">
              <div class="w-[100px]"><span class="text-red-500">*</span> 付费方式：</div>
              <a-select v-model:value="formState.paymentTypeCode" class="w-[230px]" placeholder="请选择医疗付费方式" allow-clear>
                <a-select-option v-for="(item, index) in payType" :key="index" :value="item.dictItemCode">{{ item.dictItemName }}</a-select-option>
              </a-select>
            </div>
          </div>
        </div>
        <div class="flex items-center mt-2 pr-12">
          <div class="w-[90px] pb-4">医保病种：</div>
          <a-form-item class="w-full">
            <a-input-group compact class="w-full">
              <SelectTable
                v-model:value="formState.inDiseTypeName"
                type="医保病种"
                class="!w-1/3"
                allow-clear
                :row-disabled="(row) => row.status === 1"
                @select="
                  ;(formState.inDiseTypeName = $event?.diseTypeName || ''),
                    (formState.inDiseTypeCode = $event?.diseTypeCode || ''),
                    (formState.outOprIcd9Code = $event?.oprCode || ''),
                    (formState.outOprIcd9Name = $event?.oprName || '')
                "
              />
              <a-form-item-rest>
                <a-input v-model:value="formState.inDiseTypeCode" class="!w-1/3" :disabled="true" placeholder="请选择" />
              </a-form-item-rest>
            </a-input-group>
          </a-form-item>
        </div>
      </div>
      <!-- 账户查询五期 -->
      <AccountQueryFive v-model:open="accountQueryFiveOpen" :resource-data="accountQueryData" />
      <!-- 账户查询六期 -->
      <AccountQuerySix v-model:open="accountQuerySixOpen" :resource-data="accountQueryData" :select="checkInsutypeName" @ok="onSelectCHS" />
    </div>
    <div class="flex justify-end items-center mt-2" :class="{ 'justify-between': patientInfo?.isNmiYbdj === 1 }">
      <div v-if="patientInfo?.isNmiYbdj === 1">
        <LabelValue label-class="w-[110px]" label="医保登记时间" tooltip :width="300" :value="patientInfo?.nmiYbdjTime" />
      </div>
      <div class="flex">
        <a-button type="default" class="mr-4" @click="onCancel">取消</a-button>
        <a-button type="primary" @click="onOk"> {{ patientInfo.isNmiYbdj === 1 ? '撤销' : '确定' }} </a-button>
      </div>
    </div>
  </a-modal>
</template>
<script setup>
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { post } from '@/utils/request'
import useUserStore from '@/store/user'
import { getSystemConfig } from '@/utils/systemConfig'
import AccountQuerySix from './AccountQuerySix'
import AccountQueryFive from './AccountQueryFive'

const { empId } = useUserStore()
const emit = defineEmits(['update:open', 'success'])
const props = defineProps({
  open: Boolean,
  patientInfo: {
    type: Object,
    default: () => ({})
  },
  chargeTitle: {
    type: String,
    default: ''
  },
  searchParams: {
    type: Object,
    default: () => ({})
  }
})
const formState = ref({ dpJe: '' })
const accountQueryData = ref({})
const checkInsutypeName = ref({}) //选中的险种类别
const payType = ref([])
const tabActiveKey = ref('社保卡')
const jsonStr = ref('')
const accountQueryFiveOpen = ref(false)
const accountQuerySixOpen = ref(false)
const isSixSelect = ref({})
const readCardSettingStr = ref('') //调用壳使用的json
const inAreaCode = ref('00') //00:国家医保101:上海医保 默认为 00
const loginUserDepartment = ref({})

const cardTypeEnum = {
  社保卡: {
    mdtrtCertType: '03',
    area: '*'
  },
  身份证: {
    mdtrtCertType: '02',
    area: '*'
  },
  电子凭证: {
    mdtrtCertType: '01',
    area: '*'
  },
  刷脸授权: {
    mdtrtCertType: '01',
    area: '00'
  },
  终端扫码: {
    mdtrtCertType: '01',
    area: '00'
  },
  磁卡: {
    mdtrtCertType: '00',
    area: '01'
  },
  特殊人员: {
    mdtrtCertType: '06',
    area: '01'
  }
}

//获取付费方式
const getPayTypeData = async () => {
  const { code, data, msg } = await post('/operation/opex/getDictCommonItemList', {
    dictCommonCode: 'DT00289',
    status: 1
  })
  if (code !== 0) return message.error(msg || '获取付费方式失败')
  payType.value = data
  if (payType.value && payType.value.length > 0) {
    const payType = data.filter((item) => {
      return item.dictItemName === '城乡居民基本医疗保险'
    })
    if (payType && payType.length > 0) {
      readFormState.value.payment = payType[0].dictItemCode
    }
  }
}

// 医保切换
const onTabRadioChange = async (e) => {
  let businessType = 0
  if (e.target.value === '社保卡' || e.target.value === '身份证') {
    businessType = 1
  } else if (['电子凭证', '刷脸授权', '终端扫码'].includes(tabActiveKey.value)) {
    businessType = '01101'
  } else if (e.target.value === '磁卡') {
    businessType = '00'
  }
  if (tabActiveKey.value !== '自费') {
    const res = await post('/outp/mzdj/getMedicareCardSettinglnfo', { businessType, officeid: loginUserDepartment.value.ksdm })
    if (res.code !== 0) return message.error(res.msg)
    readCardSettingStr.value = res.data
  } else {
    readCardSettingStr.value = ''
    businessType = 0
  }
}

const readFormState = ref({})
const isGb = ref(true) //false 五期 true 国平
//读取社保卡/身份证/电子凭证
const idNumber = ref('')
const readYbSrzCard = async (flag = false) => {
  let res = {}
  if (flag) {
    //无身份证识别
    if (!idNumber.value) return message.error('请输入身份证号')
    res = await post('/outp/mzdj/getReadPatientInfo', {
      type: 'RYDJ',
      brName: '',
      brSfz: idNumber.value
    })
  } else {
    if (tabActiveKey.value === '社保卡') {
      jsonStr.value = window.openExe?.readYBK(readCardSettingStr.value) //社保卡
    } else if (tabActiveKey.value === '身份证') {
      jsonStr.value = window.openExe?.readSFZ(readCardSettingStr.value) //身份证
    } else if (tabActiveKey.value === '磁卡') {
      jsonStr.value = window.openExe?.readCK(formState.value.ck, readCardSettingStr.value) //调用壳
    } else if (tabActiveKey.value === '电子凭证') {
      jsonStr.value = window.openExe?.readDZPZ(formState.value.ck, readCardSettingStr.value) //电子凭证
    } else if (tabActiveKey.value === '刷脸授权' || tabActiveKey.value === '终端扫码') {
      const params = JSON.parse(readCardSettingStr.value)
      const paramsJson = JSON.stringify({
        ...params,
        fficeid: loginUserDepartment.value.ksdm,
        officename: loginUserDepartment.value.ksmc,
        slurl: getSystemConfig('FACE_SWIPING_URL')
      })
      jsonStr.value = tabActiveKey.value === '刷脸授权' ? window.openExe?.readSL(paramsJson) : window.openExe?.readSLSM(paramsJson) //刷脸
    }
    res = await post('/outp/mzdj/getReadPatientInfo', {
      jsonStr: jsonStr.value,
      mdtrtCertNo: '',
      mdtrtCertType: cardTypeEnum[tabActiveKey.value].mdtrtCertType
    })
  }

  if (res.code !== 0) return message.error(res.msg || '读卡失败')
  if (!res.data.ybkResonse?.br_id) return message.error('无病人信息')
  const { code, data = {}, msg } = await get('/common/patient/getPatientInfo?br_id=' + res.data.ybkResonse?.br_id)
  if (code !== 0) return message.error(msg || '获取患者信息失败')
  isGb.value = res.data.isgb
  accountQueryData.value = res.data || {}
  readFormState.value = {
    ...data,
    ck: formState.value.ck,
    mdtrt_cert_no: res.data?.mdtrtCertNo,
    mdtrt_cert_type: res.data?.mdtrtCertType,
    ...res.data?.baseinfo,
    ...res.data
  }
  readFormState.value.kh = res.data.ybkResonse?.kh
  readFormState.value.ksbm_new = res.data.ybkResonse?.ksbm_new
  readFormState.value.insuplc_admdvs = res.data.ybkResonse?.insuplc_admdvs
  if (res.data.yxinsuinfo && res.data.yxinsuinfo.length > 0) {
    // yxinsuinfo 有效险种类别  insuinfo  所有险种类别
    //如果有有效险种类别，默认取第一个
    checkInsutypeName.value = JSON.parse(JSON.stringify(res.data.yxinsuinfo[0])) //赋值一个险种类别
  } else {
    //没有的话就取所有险种类别第一个
    if (res.data.insuinfo && res.data.insuinfo.length > 0) {
      checkInsutypeName.value = JSON.parse(JSON.stringify(res.data.insuinfo[0]))
    } else {
      checkInsutypeName.value = {}
    }
  }
}

// 险种类别
const onClickInsutypeName = (val) => {
  openAccountQueryModal()
  isSixSelect.value = val
}

const openAccountQueryModal = () => {
  if (!readFormState.value.kh) {
    if (tabActiveKey.value === '社保卡') return message.warning('请先读取社保卡')
    if (tabActiveKey.value === '身份证') return message.warning('请先读取身份证')
    if (tabActiveKey.value === '电子凭证') return message.warning('请先扫描电子凭证')
    if (tabActiveKey.value === '刷脸授权') return message.warning('请先读取刷脸授权')
    if (tabActiveKey.value === '终端扫码') return message.warning('请先读取终端扫码')
  }
  if (isGb.value) {
    // 国平
    accountQuerySixOpen.value = true
  } else {
    //五期
    accountQueryFiveOpen.value = true
  }
}

// 选择险种类别
const onSelectCHS = (row) => {
  checkInsutypeName.value.insutype = row.insutype
  checkInsutypeName.value.insutypeName = row.insutypeName
  checkInsutypeName.value.insuplc_admdvs = row.insuplc_admdvs
}
//
// 保存患者基础信息
const onSavePatientInfo = async () => {
  const res = await post(
    '/common/patient/savePatientInfo',
    {
      ...readFormState.value,
      brAge: getAgeUnit(readFormState.value.brAge).brAge || 0
    },
    {
      loading: true
    }
  )
  if (res.code !== 0) return message.error(res.msg || '保存医保信息失败')
}
// 保存患者医保信息
const onSavePatientYbInfo = async () => {
  const res = await post('/outp/mzdj/doSaveYbBrxx', {
    ...readFormState.value,
    brId: readFormState.value.ybkResonse?.br_id
  })
  if (res.code !== 0) return message.error(res.msg || '保存医保信息失败')
}

const onOk = async () => {
  if (!formState.value?.med_type) return message.error('请选择医疗类别')
  if (!formState.value?.paymentTypeCode) return message.error('请选择付费方式')
  if (props?.patientInfo?.isNmiYbdj === 1) {
    // isNmiYbdj === 1是已经医保登记了，需要撤销登记
    const { code, msg } = await post('/inp/zydj/doRevocationAdmissionRegistration', { inplsh: formState.value?.inplsh }, { loading: true })
    if (code !== 0) return message.error(msg)
    message.success('撤销成功')
  } else {
    await onSavePatientInfo()
    await onSavePatientYbInfo()
    const params = {
      inplsh: formState.value.inplsh,
      insutype: checkInsutypeName.value.insutype, // 险种类型
      mdtrtCertNo: readFormState.value.mdtrtCertNo, // 就诊凭证编号 磁卡：传卡内数据 电子凭证：传ecToken 身份证：不传 医保卡：传身份证号
      mdtrtCertType: readFormState.value.mdtrtCertType, // 就诊凭证类型
      med_type: formState.value.med_type, // 医疗类别
      paymentTypeCode: formState.value?.paymentTypeCode, // 收费
      ybkh: readFormState.value?.kh, // 人员编号,
      inDiseTypeName: formState.value.inDiseTypeName,
      inDiseTypeCode: formState.value.inDiseTypeCode,
      outOprIcd9Code: formState.value.outOprIcd9Code,
      outOprIcd9Name: formState.value.outOprIcd9Name
    }
    // if (tabActiveKey.value === '01') {
    //   params.mdtrtCertNo = readFormState.value?.mdtrtCertNo // 电子凭证ecToken
    // }
    // if (tabActiveKey.value === '03') {
    //   params.mdtrtCertNo = readFormState.value?.brSfz
    // }
    const { code, msg } = await post('/inp/zydj/inpMedicareRegistration', params, { loading: true })
    if (code !== 0) return message.error(msg)
    message.success('保存成功')
  }
  emit('success')
  onCancel()
}
const getLoginUserDepartment = async () => {
  const res = await post('/common/masterData/getByYsbhDepartment', { empId: empId })
  if (res.code !== 0) message.error(res.msg || '获取登录人科室失败')
  loginUserDepartment.value = res?.data || {}
}

const filterType = () => {
  // area为01为上海五期医保单独处理  其余按国家医保处理
  if (inAreaCode.value) {
    const tab = []
    for (const key in cardTypeEnum) {
      if (Object.hasOwnProperty.call(cardTypeEnum, key)) {
        const element = cardTypeEnum[key]
        if (inAreaCode.value === '01') {
          if (element.area === '01' || element.area === '*') {
            element.name = key
            tab.push(element)
          }
        } else {
          if (element.area === '00' || element.area === '*') {
            element.name = key
            tab.push(element)
          }
        }
      }
    }
    return tab
  } else {
    message.error('请联系管理员设置医保区域代码')
    return []
  }
}

const onCancel = () => {
  emit('update:open', false)
}

watch(
  () => props.open,
  (val) => {
    if (val) {
      getPayTypeData()
      formState.value = { ...props.patientInfo, med_type: props.patientInfo.inpTypeCode }
      idNumber.value = props.patientInfo?.brSfz
    } else {
      readFormState.value = {}
      formState.value = {}
      checkInsutypeName.value = {}
      idNumber.value = ''
    }
  },
  { immediate: true }
)
onMounted(() => {
  inAreaCode.value = getSystemConfig('NMI_REGION_CODE') //00:国家医保101:上海医保 默认为 00
  getLoginUserDepartment()
})
</script>

<style lang="less" scoped>
.ant-tag-checkable-checked {
  color: #fff;
  background-color: var(--primary-color);
}
</style>
